package com.neuedu.it.mylink.controller;

import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.neuedu.it.mylink.controller.vo.Result;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.Date;

@RestController
@RequestMapping("/api/v1/oss")
public class OssController {
    private OSS ossClient;
    public OssController(){
        try {
            ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
            clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
            this.ossClient = OSSClientBuilder.create()
                    .endpoint("https://oss-cn-hangzhou.aliyuncs.com")
                    .region("oss-cn-guangzhou")
                    .credentialsProvider(CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider())
                    .clientConfiguration(clientBuilderConfiguration)
                    .build();
        }catch (Exception ex){
            ex.printStackTrace();
            throw new RuntimeException(ex);
        }
    }

    @PostMapping("/upload")
    public Result upload(MultipartFile photo) {
        try{
            String objectName=new Date().getTime()+photo.getOriginalFilename();
            InputStream inputStream =photo.getInputStream();
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest("hn-link2", objectName, inputStream);
            // 创建PutObject请求。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            return new Result(2000,"上传成功",result.getResponse().getUri());
        }catch (Exception ex){
            ex.printStackTrace();
            throw new RuntimeException(ex);
        }
    }
    @PostMapping("/delete")
    public Result delete(String objectName) {
        ossClient.deleteObject("hn-link2",objectName);
        return new Result(2000,"删除成功",null);
    }

}
